﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using G.Navigate;
using System.Xml;
using System.ServiceModel.Syndication;
using G.Reader.Data;

namespace G.Reader.View
{
    public partial class RSSListPage : GBasePage
    {
        private readonly List<KeyValuePair> defualtRss = new List<KeyValuePair>() { new KeyValuePair("http://www.wpdang.com/feed", "WPDang"), 
            new KeyValuePair("http://cnbeta.feedsportal.com/c/34306/f/624776/index.rss", "cnBeta.COM") ,
            new KeyValuePair("http://blog.sina.com.cn/rss/1366169612.xml","唯有中华"),
            new KeyValuePair("http://blog.sina.com.cn/rss/1071924215.xml","金鸿")
        };
        public RSSListPage()
        {
            InitializeComponent();
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (book == null)
            {
                if (this.NavigationContext.QueryString.ContainsKey("bookid"))
                {
                    int id = int.Parse(this.NavigationContext.QueryString["bookid"]);
                    book = GloabalData.Instance.BookDataBase.BookTable.FirstOrDefault(a => a.ID == id);
                    this.PageTitle.Text = book.BookName;
                    LoadRSS(book.Address);
                }
                else
                {
                    this.ApplicationBar.IsVisible = true;
                    txtRSSAddress.Visibility = System.Windows.Visibility.Visible;
                    slideup_add.ItemsSource = defualtRss;
                }
            }
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            LoadRSS(txtRSSAddress.Text);
        }

        private void LoadRSS(string url)
        {
            this.RegisterLoading(null);
            WebClient client = new WebClient();
            client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
            client.OpenReadAsync(new Uri(url, UriKind.Absolute));
        }
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            if (slideup_add.IsOpen)
            {
                slideup_add.IsOpen = false;
                e.Cancel = true;
            }
        }
        BookInfo book;
        void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                try
                {
                    XmlReader response = XmlReader.Create(e.Result);
                    SyndicationFeed feeds = SyndicationFeed.Load(response);
                    List<FeedItem> items = new List<FeedItem>();
                    if (book == null)
                    {
                        book = new BookInfo() { BookName = feeds.Title.Text, Address = txtRSSAddress.Text, BookType = BookType.RSS };
                        this.PageTitle.Text = book.BookName;
                        GloabalData.Instance.BookDataBase.BookTable.InsertOnSubmit(book);
                        GloabalData.Instance.BookDataBase.SubmitChanges();
                    }
                    foreach (SyndicationItem item in feeds.GetRss20Formatter().Feed.Items)
                    {
                        FeedItem feedItem = new FeedItem();
                        feedItem.Title = item.Title.Text;
                        feedItem.PubDate = item.PublishDate.DateTime;
                        if (item.Authors != null && item.Authors.Count > 0)
                            feedItem.Author = item.Authors[0].Name;
                        feedItem.Content = item.Summary.Text;
                        feedItem.Link = item.Links[0].Uri;
                        items.Add(feedItem);
                    }
                    listbox_rsslist.ItemsSource = items;
                    this.ApplicationBar.IsVisible = false;
                    this.txtRSSAddress.Visibility = System.Windows.Visibility.Collapsed;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("解析失败，请检查地址是否正确");
                }

            }
            else
            {
                MessageBox.Show("下载失败，请检查地址是否正确");
            }
            this.UnregisterLoading();
        }

        private void listbox_rsslist_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listbox_rsslist.SelectedItem != null)
            {

                FeedItem feedItem = listbox_rsslist.SelectedItem as FeedItem;
                this.NavigationService.Navigate("/View/RSSDetailPage.xaml", feedItem);
                listbox_rsslist.SelectedItem = null;
            }
        }

        private void menuDetail_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement f = sender as FrameworkElement;
            this.NavigationService.Navigate("/View/WebBrowserPage.xaml?url=" + (f.DataContext as FeedItem).Link.AbsoluteUri);

        }

        private void btndefualt_Click(object sender, EventArgs e)
        {
            slideup_add.IsOpen = !slideup_add.IsOpen;
        }

        private void slideup_add_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            slideup_add.IsOpen = false;
            if (slideup_add.SelectedItem != null)
            {
                KeyValuePair kv = slideup_add.SelectedItem as KeyValuePair;
                this.txtRSSAddress.Text = kv.Key;
                LoadRSS(kv.Key);
            }
            slideup_add.SelectedItem = null;
        }

        private void menuFaviorit_Click(object sender, RoutedEventArgs e)
        {
            FrameworkElement f = sender as FrameworkElement;
            FeedItem item = f.DataContext as FeedItem;
            BookInfo newsbook = new BookInfo() { BookName = item.Title, Address = item.Link.AbsoluteUri, BookType = BookType.News };
            GloabalData.Instance.BookDataBase.AddBook(new System.IO.MemoryStream(item.Content.GetBytes()), newsbook);
        }
    }
}